package com.liuzh.kaoyanspringboot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuzh.kaoyanspringboot.common.Constants;
import com.liuzh.kaoyanspringboot.controller.dto.UserDTO;
import com.liuzh.kaoyanspringboot.entity.Menu;
import com.liuzh.kaoyanspringboot.entity.User;
import com.liuzh.kaoyanspringboot.exception.ServiceException;
import com.liuzh.kaoyanspringboot.mapper.RoleMapper;
import com.liuzh.kaoyanspringboot.mapper.RoleMenuMapper;
import com.liuzh.kaoyanspringboot.mapper.UserMapper;
import com.liuzh.kaoyanspringboot.service.MenuService;
import com.liuzh.kaoyanspringboot.service.UserService;
import com.liuzh.kaoyanspringboot.utils.TokenUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-02-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final Log LOG = Log.get();
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuService menuService;
    @Resource
    private UserMapper userMapper;


    /**
     * 根据 userDTO 获取数据库里的 user 信息
     * @param userDTO
     * @param login    login 为 true 时配对 password
     * @return
     */
    private User getUserInfo(UserDTO userDTO, boolean login){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        if(login == true){
            queryWrapper.eq("password",userDTO.getPassword());
        }
        User one;
        try {
            one = getOne(queryWrapper);
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }

    /**
     * 用户登录
     * @param userDTO
     * @return
     */
    @Override
    public UserDTO login(UserDTO userDTO) {
        User one = getUserInfo(userDTO,true);
        if(one != null) {
            BeanUtil.copyProperties(one,userDTO,true); //忽略大小写
            String token = TokenUtils.genToken(one.getId().toString(),one.getPassword()); //设置token
            userDTO.setToken(token);
            // 获取用户角色
            String role = one.getRole();
            // 设置用户菜单列表
            userDTO.setMenus(getRoleMenus(role));
            return userDTO;
        } else {
            throw new ServiceException(Constants.CODE_666, "用户名或密码错误");
        }
    }

    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @Override
    public User register(UserDTO userDTO) {
        User one = getUserInfo(userDTO,false);
        if(one == null) {
            one = new User();
            BeanUtil.copyProperties(userDTO, one, true); //忽略大小写
            save(one);
            return one;
        } else {
            throw new ServiceException(Constants.CODE_666, "用户已存在");
        }
    }

    @Override
    public UserDTO getbyUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User one = getOne(queryWrapper);
        UserDTO res = new UserDTO();
        BeanUtil.copyProperties(one,res,true);
        List<Menu> menus = getRoleMenus(res.getRole());
        res.setMenus(menus);
        return res;
    }

    @Override
    public Page<User> findPage(Page<User> page, String username, String nickname, String email, String address) {
        return userMapper.findPage(page,username,nickname,email,address);
    }


    /**
     * 获取当前角色菜单列表
     * @param role
     * @return
     */
    private List<Menu> getRoleMenus(String role) {
        Integer roleId = roleMapper.selectIdByFlag(role);
        // 根据角色id，从角色菜单表中，查出角色所对应的所有菜单 id 集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);
        // 从菜单表中查出系统所有菜单
        List<Menu> menus = menuService.findMenus();
        // 筛选当前用户角色的菜单
        List<Menu> roleMenus = new ArrayList<>();
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) { //若 menuIds数组集合里包含 menus元素的 id
                roleMenus.add(menu);  // 则将 menus 里的该元素 添加到 该角色的菜单
            }
            List<Menu> children = menu.getChildren();
            // 移除 children 里面不在 menuIds集合中的元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }


}
